package com.steptime.thread.reentrantlock;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示：公平和非公平锁的区别
 */
public class FairDemo {

    public static void main(String[] args) {
        PrintQueue printQueue = new PrintQueue();
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(new Job(printQueue));
        }

        for (int i = 0; i < 5; i++) {
            threads[i].start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    static class Job implements Runnable{
        private PrintQueue printQueue;

        public Job(PrintQueue printQueue) {
            this.printQueue = printQueue;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"开始打印");
            printQueue.printInfo();
            System.out.println(Thread.currentThread().getName()+"打印结束");
        }
    }

    static class PrintQueue {
        //可重入锁的参数可以设置公平和非公平锁
        private static ReentrantLock reentrantLock = new ReentrantLock(true);

        public void printInfo() {
            reentrantLock.lock();
            try {
                int time = new Random().nextInt(10) + 1;
                System.out.println(Thread.currentThread().getName() + "打印需要" + time + "秒");
                try {
                    Thread.sleep(time * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                reentrantLock.unlock();
            }

            reentrantLock.lock();
            try {
                int time = new Random().nextInt(10) + 1;
                System.out.println(Thread.currentThread().getName() + "打印需要" + time + "秒");
                try {
                    Thread.sleep(time * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                reentrantLock.unlock();
            }
        }
    }

}
